package com.lzx.adx.report.controller.v1.xiaomi;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.CZCovertXMWifiEventTypeEnums;
import com.lzx.adx.report.enums.ElmCovertXiaoMiEventTypeEnums;
import com.lzx.adx.report.model.xiaomi.XiaoMiRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/xiaomi/cz")
@Slf4j
public class XiaoMiCzController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;

    public static final String apiDesc = "小米创智";


    @GetMapping("/report")
    public ResponseEntity report(XiaoMiRequest requestParams, HttpServletRequest request) {
        log.info("接收到xiaomi-elm【{}】的请求参数为{}", apiDesc, JsonUtils.toJsonString(requestParams));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(requestParams);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(requestParams));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(requestParams.getDspId());

        String finalUrl = KkHeper.covertChuangZhiUrl(accountDTO, requestParams, reportDTO);

        log.info("账号为{},完整的小米-创智 请求地址为{}", requestParams.getDspId(), finalUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 小米接收了-创智，上报的接口，响应的结果为{}", requestParams.getDspId(), body);

        return ResponseEntity.ok(new Result());
    }


    /**
     * 饿了么回传
     *
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId, String tnaEvent) throws Exception {
        log.info("小米接收了创智回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("小米接收了创智请求流水号空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }



        //设置默认的事件
        String defaultTnaEvent = "defaultTnaEvent";
        if (StringUtils.isNotBlank(tnaEvent)) {
            defaultTnaEvent = CZCovertXMWifiEventTypeEnums.getXiaoMiCode(tnaEvent);
            if (StringUtils.isBlank(defaultTnaEvent)) {
                log.info("事件有误,小米接收了创智回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
                return ResponseEntity.ok(new Result());
            }
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);

        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        //获取配置的秘钥，获取不到标识没关注此事件
        String singKey = jsonObject.getString(defaultTnaEvent);
        if (StringUtils.isBlank(singKey)) {
            log.info("账户id{}请求流水号{} 不关注此事件{}", reportDTO.getDspId(), requestId, tnaEvent);
            return ResponseEntity.ok(new Result());
        }
        String convType;
        if (StringUtils.isNotBlank(tnaEvent)) {
            convType = defaultTnaEvent;
        } else {
            convType = jsonObject.getString("defaultConvType");
            if (StringUtils.isBlank(convType)) {
                log.info("defaultConvType事件有误,小米接收了创智回调信息 账号{}请求流水号{} 事件{}", reportDTO.getDspId(), requestId, tnaEvent);
                return ResponseEntity.ok(new Result());
            }
        }

        reportDTO.setResultType(tnaEvent);
        reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,tnaEvent);

        Double per = jsonObject.getDouble("per");
        if (Objects.nonNull(per)) {
            if(!AdPerUtil.randomPer(per)) {
                log.info("dspId为{}流水号为 {} 超出了比例外，超出比例值{}", reportDTO.getDspId(), reportDTO.getBizRequestId(), per);
                return ResponseEntity.ok(new Result());
            }
        }
        log.info("账号id{}创智给小米回传的状态{} 秘钥{}", reportDTO.getDspId(), defaultTnaEvent, singKey);
        Map<String, String> reqMap = new LinkedHashMap<>();
        reqMap.put("callback", URLEncoderDecoderTool.encodeURL(reportDTO.getCallback()));
        if (StringUtils.isNotBlank(reportDTO.getOaid())) {
            reqMap.put("oaid", reportDTO.getOaid());
        } else if (StringUtils.isNotBlank(reportDTO.getImei())) {
            reqMap.put("imei", reportDTO.getImei());
        }
        reqMap.put("conv_time", String.valueOf(System.currentTimeMillis()));
        reqMap.put("convType", convType);
        String url = URLUtil.buildQuery(reqMap, StandardCharsets.UTF_8);
        String sign = SecureUtil.md5(url + singKey);
        String resultUrl = accountDTO.getSspApiUrl() + "?" + url + "&sign=" + sign;
        log.info("账号id{}请求流水号{}秘钥{}创智给小米回传的完整地址为{}", reportDTO.getDspId(), requestId, singKey, resultUrl);
        String rsult = HttpUtil.get(resultUrl);
        log.info("账号id{}请求流水号{}秘钥{}创智给小米回传的结果为{}", reportDTO.getDspId(), requestId, singKey, rsult);
        return ResponseEntity.ok(new Result());
    }


    /**
     * 饿了么回传
     *
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/tc/callback")
    public ResponseEntity tcCallBackUrl(String requestId, String tnaEvent) throws Exception {
        log.info("小米接收了创智同城回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("小米接收了创智同城请求流水号空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        if(StringUtils.isBlank(tnaEvent)){
            tnaEvent="active";
        }

        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(tnaEvent);
            reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,tnaEvent);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        JSONObject jsonObject = JSONObject.parseObject(accountDTO.getSspExtend());
        String key = jsonObject.getString(tnaEvent);
        if(StringUtils.isBlank(key)){
            log.info("小米收到创智同城的回调信息当前流水号：{}，事件类型{}不合法，不做数据回传", requestId,tnaEvent);
            return ResponseEntity.ok(new Result());
        }


        Map<String, String> reqMap = new LinkedHashMap<>();
        reqMap.put("callback", URLEncoderDecoderTool.encodeURL(reportDTO.getCallback()));
        if (StringUtils.isNotBlank(reportDTO.getOaid())) {
            reqMap.put("oaid", reportDTO.getOaid());
        } else if (StringUtils.isNotBlank(reportDTO.getImei())) {
            reqMap.put("imei", reportDTO.getImei());
        }
        reqMap.put("conv_time", String.valueOf(System.currentTimeMillis()));
        reqMap.put("convType", key);
        String url = URLUtil.buildQuery(reqMap, StandardCharsets.UTF_8);
        String sign = SecureUtil.md5(url + jsonObject.getString(key));
        String resultUrl = accountDTO.getSspApiUrl() + "?" + url + "&sign=" + sign;
        log.info("账号id{}请求流水号{} 秘钥{} 创智同城给小米回传的完整地址为{}", reportDTO.getDspId(), requestId, key, resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账号id{}请求流水号{} 秘钥{} 创智同城给小米回传的结果为{}", reportDTO.getDspId(), requestId, key, result);
        return ResponseEntity.ok(new Result());
    }


    /**
     * 创智通用-小米
     *
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/common/callback")
    public ResponseEntity commonCallBackUrl(String requestId, String tnaEvent) throws Exception {

        log.info("小米接收了创智回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("小米接收了创智请求流水号空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //回传为空就代表激活
        if(StringUtils.isBlank(tnaEvent)){
            tnaEvent="active";
        }

        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        JSONObject jsonObject = JSONObject.parseObject(accountDTO.getSspExtend());
        String code = jsonObject.getString(tnaEvent);
        String key = jsonObject.getString(code);
        if (StringUtils.isBlank(code)){
            log.info("账号{},接收了创智的的回调信息当前流水号：{}，事件类型{}不合法，不做数据回传",reportDTO.getDspId(), requestId,tnaEvent);
            return ResponseEntity.ok(new Result());
        }

        reportDTO.setResultType(tnaEvent);
        reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,tnaEvent);

        //2.从缓存加载配置
        Map<String, String> reqMap = new LinkedHashMap<>();
        reqMap.put("callback", URLEncoderDecoderTool.encodeURL(reportDTO.getCallback()));
        if (StringUtils.isNotBlank(reportDTO.getOaid())) {
            reqMap.put("oaid", reportDTO.getOaid());
        } else if (StringUtils.isNotBlank(reportDTO.getImei())) {
            reqMap.put("imei", reportDTO.getImei());
        }
        reqMap.put("conv_time", String.valueOf(System.currentTimeMillis()));
        reqMap.put("convType", code);
        String url = URLUtil.buildQuery(reqMap, StandardCharsets.UTF_8);
        String sign = SecureUtil.md5(url + jsonObject.getString(code));
        String resultUrl = accountDTO.getSspApiUrl() + "?" + url + "&sign=" + sign;
        log.info("账号id{}请求流水号{} 秘钥{} 创智给小米回传的完整地址为{}", reportDTO.getDspId(), requestId, key, resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账号id{}请求流水号{} 秘钥{} 创智给小米回传的结果为{}", reportDTO.getDspId(), requestId, key, result);
        return ResponseEntity.ok(new Result());
    }




    /**
     * 创智通用-小米
     *  注册
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/register/common/callback")
    public ResponseEntity commonRegisterCallBackUrl(String requestId, String tnaEvent) throws Exception {

        log.info("小米接收了创智回调信息 请求流水号{} 事件{}", requestId, tnaEvent);
        if (StringUtils.isBlank(requestId)) {
            log.info("小米接收了创智请求流水号空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //回传为空就代表激活
        if(StringUtils.isBlank(tnaEvent)){
            tnaEvent="register";
        }

        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        JSONObject jsonObject = JSONObject.parseObject(accountDTO.getSspExtend());
        String code = jsonObject.getString(tnaEvent);
        String key = jsonObject.getString(code);
        if (StringUtils.isBlank(code)){
            log.info("账号{},接收了创智的的回调信息当前流水号：{}，事件类型{}不合法，不做数据回传",reportDTO.getDspId(), requestId,tnaEvent);
            return ResponseEntity.ok(new Result());
        }

        reportDTO.setResultType(tnaEvent);
        reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,tnaEvent);

        //2.从缓存加载配置
        Map<String, String> reqMap = new LinkedHashMap<>();
        reqMap.put("callback", URLEncoderDecoderTool.encodeURL(reportDTO.getCallback()));
        if (StringUtils.isNotBlank(reportDTO.getOaid())) {
            reqMap.put("oaid", reportDTO.getOaid());
        } else if (StringUtils.isNotBlank(reportDTO.getImei())) {
            reqMap.put("imei", reportDTO.getImei());
        }
        reqMap.put("conv_time", String.valueOf(System.currentTimeMillis()));
        reqMap.put("convType", code);
        String url = URLUtil.buildQuery(reqMap, StandardCharsets.UTF_8);
        String sign = SecureUtil.md5(url + jsonObject.getString(code));
        String resultUrl = accountDTO.getSspApiUrl() + "?" + url + "&sign=" + sign;
        log.info("账号id{}请求流水号{} 秘钥{} 创智给小米回传的完整地址为{}", reportDTO.getDspId(), requestId, key, resultUrl);
        String result = HttpUtil.get(resultUrl);
        log.info("账号id{}请求流水号{} 秘钥{} 创智给小米回传的结果为{}", reportDTO.getDspId(), requestId, key, result);
        return ResponseEntity.ok(new Result());
    }





    /**
     * 是否在比例范围内
     *
     * @param per
     * @return
     */
    private static boolean shouldIdentifyAd(Double per) {
        Random random = new Random();
        double randomValue = random.nextDouble(); // 生成到1之间的随机数
        log.info("随机数为{}", randomValue);
        return randomValue > per;
    }
}
